package fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cyan.tools.util.RxBus;
import com.example.menhoo.toollibrary.android.log.Log;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.util.LogUtils;
import com.socks.library.KLog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import app.AutoFragment;
import application.AppApplication;
import application.HttpUrlConstant;
import application.UIHttpURL;
import bean.AppTipNumBean;
import bean.DeptConfig;
import bean.DoListNotifySourceBean;
import bean.Result;
import bean.WorkFlow;
import interfaces.IReturnObject;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import mainUI.AppFragment;
import menhoo.com.i8officelibrary.R;
import model.AppModel;
import model.TabModel;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import utils.SharePreferHelper;
import utils.TipsUtils;
import view.recyclerview.CommonAdapter;
import view.recyclerview.HeaderAndFooterWrapper;

/**
 * Created by yanglei on 15/9/17.
 */
public class APP extends AppFragment {

    private static final String TAG = "APP";

    //    DragGridView gridView;
    RecyclerView recyclerView;
    RecyclerView recyclerViewBM;
    RecyclerView gridview;
    SwipeRefreshLayout refreshLayout;
    MyGridViewAdapter adapter;
    Button menu_ok;
    final Map<String, AppTipNumBean> tipNumList = new HashMap<>();
    HeaderAndFooterWrapper mAdapter;
    CommonAdapter<WorkFlow> wadapter;
    CommonAdapter<WorkFlow> wadapterBM;
    private Observable<String> observable;
    private Disposable disposable;
    private String[] codes = {"Mobile.Workflow", "important_notice", "important_file", "news", "Mobile.Calendar", "dept_notice", "Mobile.Docs", "public_notice"};
    private String[] titles = {"网上办公", "重要通知", "重要文件", "要闻资讯", "日程安排", "部门通知", "部门文件", "公示公告"};
    private int[] pics = {R.mipmap.ic_workflow, R.raw.zhongyao, R.raw.zhongyaowenjian, R.raw.yaowenzixun, R.mipmap.ic_calar, R.raw.bumen, R.mipmap.ic_file, R.mipmap.ic_public_notice};
    private int workflowTipsNum = 0;
    private View bm_todo_title;
    private boolean isShowDep = false;
    private boolean canOfficeClick = false;

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContextView(R.layout.fragment_app);
    }

    @Override
    public void init() {

        super.init();
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeColors(ContextCompat.getColor(getActivity(), R.color.tab_top_bg));
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getOfficePending();
                getOfficePendingBM();
                getAppTipsNum();
            }
        });
        setCustomRightButton(R.layout.tab_app_title_right);
        rootView.findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSimpleDialogMessage("是否要退出登录?", new IReturnObject() {
                    @Override
                    public void returnResult(Object result) {
                        //向网站发送登出接口,解除阿里云推送
                        DeleteDeviceToken(AppApplication.getALiYunDeviceId(), new IReturnObject() {
                            @Override
                            public void returnResult(Object result) {
                            }
                        });


                    }
                }, true, true);
            }
        });
        //
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
        recyclerViewBM = (RecyclerView) rootView.findViewById(R.id.recyclerview_bm);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerViewBM.setLayoutManager(new LinearLayoutManager(getActivity()));
        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.tab_apps_header, null);
        headerView.findViewById(R.id.todo_title).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent it = new Intent();
                if (isShowDep && canOfficeClick) {
                    it.setClassName(getActivity(), "com.i8office.android.zhihuixinwu.ui.dep.OfficeNewActivity");
                } else {
                    it.setClassName(getActivity(), "com.i8office.android.zhihuixinwu.ui.OfficeActivity");
                }
                startActivity(it);

            }
        });
        bm_todo_title = rootView.findViewById(R.id.bm_todo_title);
        bm_todo_title.setVisibility(View.GONE);
        bm_todo_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it = new Intent();
                if (isShowDep && canOfficeClick) {
                    it.setClassName(getActivity(), "com.i8office.android.zhihuixinwu.ui.dep.OfficeNewActivity");
                    it.putExtra("page", 1);
                } else {
                    it.setClassName(getActivity(), "com.i8office.android.zhihuixinwu.ui.OfficeActivity");
                }
                startActivity(it);

            }
        });
        gridview = (RecyclerView) headerView.findViewById(R.id.item_grid);
        gridview.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        adapter = new MyGridViewAdapter(context);
        gridview.setAdapter(adapter);
        wadapter = new CommonAdapter<WorkFlow>(getActivity(), R.layout.item_pending) {
            @Override
            protected void convert(view.recyclerview.ViewHolder holder, final WorkFlow data, int position) {
                holder.setText(R.id.title, data.getDocumentTitle());
                holder.setText(R.id.content, data.getSequenceName() + " " + data.getSequenceNumber());
                holder.setText(R.id.date, TextUtils.isEmpty(data.getClosedOrHairTime()) ? "" : data.getClosedOrHairTime().substring(0, 10));
                holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent();
                        it.setClassName(getActivity(), "com.i8office.android.zhihuixinwu.ui.DetailActivity");
                        it.putExtra("workFlow", data);
                        it.putExtra("from", "main");
                        startActivity(it);
                    }
                });
            }
        };
        wadapterBM = new CommonAdapter<WorkFlow>(getActivity(), R.layout.item_pending_bm) {
            @Override
            protected void convert(view.recyclerview.ViewHolder holder, final WorkFlow data, int position) {
                holder.setText(R.id.title, data.getDocumentTitle());
                holder.setText(R.id.content,data.getMessageTitle());
                holder.setText(R.id.date, TextUtils.isEmpty(data.getClosedOrHairTime()) ? "" : data.getClosedOrHairTime().substring(0, 10));
                holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent();
                        it.setClassName(getActivity(), "com.i8office.android.zhihuixinwu.ui.dep.DetailDepActivity");
                        it.putExtra("workFlow", data);
                        it.putExtra("from", "main");
                        startActivity(it);
                    }
                });
            }
        };
        mAdapter = new HeaderAndFooterWrapper(wadapter);
        headerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mAdapter.addHeaderView(headerView);
        recyclerView.setAdapter(mAdapter);
        recyclerViewBM.setAdapter(wadapterBM);
        recyclerViewBM.setVisibility(View.GONE);
//        getAppTipsNum();
        hideContent();
        refreshLayout.setRefreshing(true);
        observable = RxBus.get().register("submitSuccess", String.class);
        disposable = observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(final String data) throws Exception {
                getOfficePending();
                getOfficePendingBM();
                getAppTipsNum();
            }
        });
        requestData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
        if (observable != null) RxBus.get().unregister("add_staff", observable);
    }

    /**
     * 获取App栏目的未读数量
     */
    private void getAppTipsNum() {
        getWorkFloawTipsTotal();
        tipNumList.clear();
        String tipListStr = SharePreferHelper.getStrValues("tipList", "");

        Gson gson = new Gson();
        final List<DoListNotifySourceBean.NotifySourcesBean> tipList = gson.fromJson(tipListStr, new TypeToken<List<DoListNotifySourceBean.NotifySourcesBean>>() {
        }.getType());
        if (tipList != null) {
            for (DoListNotifySourceBean.NotifySourcesBean sourcesBean : tipList) {
                if (sourcesBean.getAppCode().equals("Mobile.Workflow")) {
                    continue;
                }
                TipsUtils.getNotifyNum(sourcesBean.getAppCode(), sourcesBean.getNSUrl(), new TipsUtils.onGetTipNumSuccess() {
                    @Override
                    public void setOnGetTipNumSuccess(String AppCode, String num) {
                        tipNumList.put("AppCode", new AppTipNumBean(AppCode, num));
                        HandlerUtil.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (adapter != null) {
                                    adapter.notifyDataSetChanged();
                                    mAdapter.notifyDataSetChanged();
                                }
                            }
                        });
                    }
                });
            }
        }

        TipsUtils.getIMUnReadTotalNum(new TipsUtils.onGetTipNumSuccess() {
            @Override
            public void setOnGetTipNumSuccess(String AppCode, String num) {
                tipNumList.put("IM", new AppTipNumBean("IM", num));
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                    mAdapter.notifyDataSetChanged();
                }
            }
        });


    }

    /**
     * 请求所有app数据
     */
    private void requestData() {
        List<TabModel> modes = new ArrayList<>();
        for (int i = 0; i < codes.length; i++) {
            AppModel model = new AppModel();
            model.code = codes[i];
            model.name = titles[i];
            model.type = "importNotice";
            if (model.code.equals("Mobile.Workflow")) {
                model.htmlUrl = "";
                model.type = "workflow";
            } else if (model.code.equals("Mobile.Calendar")) {
                model.htmlUrl = "/Mobile/Calendar";
            } else {
                model.type = "news";
                model.htmlUrl = HttpUrlConstant.getWebSiteFullUrl2() + "/" + HttpUrlConstant.getNewsList + "?catogeryName=" + model.name;
            }
            model.icon = pics[i];
            modes.add(model);
        }
        adapter.setList(modes);
        mAdapter.notifyDataSetChanged();
        showContent();
        getIsShowDep();
    }

    @Override
    public void onResume() {
        super.onResume();
        getAppTipsNum();
        getOfficePending();
        getOfficePendingBM();
    }

    public void getIsShowDep() {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .build();
        String urlF = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.checkHasDept) + "?__session__=" + AppApplication.getSession();
        KLog.e("urlF:" + urlF);
        Request request = new Request.Builder()
                .url(urlF)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                canOfficeClick = true;
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                canOfficeClick = true;
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                });
                try {
                    String result = response.body().string();
                    KLog.e("result:" + result);
                    final Result<DeptConfig> data = new Gson().fromJson(result, new TypeToken<Result<DeptConfig>>() {
                    }.getType());
                    HandlerUtil.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            isShowDep = data.getData().haveDeptConfig;
                            if (isShowDep) {
//                                bm_todo_title.setVisibility(View.VISIBLE);
                                recyclerViewBM.setVisibility(View.VISIBLE);
                            } else {
//                                bm_todo_title.setVisibility(View.GONE);
                                recyclerViewBM.setVisibility(View.GONE);
                            }
                        }
                    });
                } catch (Exception e) {
                    KLog.e("出错了" + e.toString());
                }
            }
        });
    }


    public void getOfficePending() {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("PageNumber", "1")
                .add("PageSize", "5")
                .build();
        String urlF = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.getPendingInfo) + "?__session__=" + AppApplication.getSession();
        KLog.e("urlF:" + urlF);
        Request request = new Request.Builder()
                .url(urlF)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                });
                try {
                    String result = response.body().string();
                    KLog.e("result:" + result);
                    final Result<List<WorkFlow>> data = new Gson().fromJson(result, new TypeToken<Result<List<WorkFlow>>>() {
                    }.getType());
                    HandlerUtil.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (data != null && data.getData() != null) {
                                wadapter.setList(data.getData());
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    });
                } catch (Exception e) {
                    KLog.e("出错了" + e.toString());
                }
            }
        });
    }

    public void getOfficePendingBM() {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("PageNumber", "1")
                .add("PageSize", "5")
                .build();
        String urlF = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.getPendingInfoBM) + "?__session__=" + AppApplication.getSession();
        KLog.e("urlF:" + urlF);
        Request request = new Request.Builder()
                .url(urlF)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                });
                try {
                    String result = response.body().string();
                    KLog.e("result:" + result);
                    final Result<List<WorkFlow>> data = new Gson().fromJson(result, new TypeToken<Result<List<WorkFlow>>>() {
                    }.getType());
                    HandlerUtil.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (data != null && data.getData() != null) {
                                wadapterBM.setList(data.getData());
                            }
                        }
                    });
                } catch (Exception e) {
                    KLog.e("出错了" + e.toString());
                }
            }
        });
    }

    public void getWorkFloawTipsTotal() {
        Executors.newCachedThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                int num1 = getWorkFloawTipsNum();
                int num2 = getWorkFloawDepTipsNum();
                workflowTipsNum = num1 + num2;
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (adapter != null && mAdapter != null) {
                            adapter.notifyDataSetChanged();
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        });
    }

    public int getWorkFloawTipsNum() {
        OkHttpClient client = new OkHttpClient();
        String urlF = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.getWorkFlowTipsNum) + "?__session__=" + AppApplication.getSession();
        KLog.e("urlF:" + urlF);
        FormBody formBody = new FormBody
                .Builder()
                .build();
        Request request = new Request.Builder()
                .post(formBody)
                .url(urlF)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            KLog.e("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            boolean succeed = jsonObject.optBoolean("Succeed", false);
            if (succeed) {
                final int tipsNum = jsonObject.optJSONObject("Data").optInt("Total");
                return tipsNum;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int getWorkFloawDepTipsNum() {
        OkHttpClient client = new OkHttpClient();
        String urlF = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.getWorkFlowTipsNumDEP) + "?__session__=" + AppApplication.getSession();
        KLog.e("urlF:" + urlF);
        FormBody formBody = new FormBody
                .Builder()
                .build();
        Request request = new Request.Builder()
                .post(formBody)
                .url(urlF)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            KLog.e("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            boolean succeed = jsonObject.optBoolean("Succeed", false);
            if (succeed) {
                final int tipsNum = jsonObject.optJSONObject("Data").optInt("Total");
                return tipsNum;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    class MyGridViewAdapter extends CommonAdapter<TabModel> {

        public MyGridViewAdapter(Context context) {
            super(context, R.layout.adapter_app_item);
        }

        public void notifyNumchange() {
            notifyDataSetChanged();
        }

        @Override
        protected void convert(view.recyclerview.ViewHolder holder, final TabModel model, int position) {
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.text = holder.getView(R.id.textView);
            viewHolder.img = holder.getView(R.id.imageView);
            viewHolder.ll_container = holder.getView(R.id.ll_container);
            viewHolder.tv_point_num = holder.getView(R.id.tv_point_num);
            viewHolder.ll_point = holder.getView(R.id.ll_point);

            viewHolder.text.setText(model.name);
            if (Check.isEmpty(model.iconUrl)) {
                viewHolder.img.setImageResource(model.icon);
            } else {
                getIconLoader().display(viewHolder.img, model.iconUrl, new BitmapLoadCallBack<ImageView>() {
                    @Override
                    public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                        imageView.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {
                        imageView.setImageResource(R.drawable.load_failed);
                    }
                });
            }
            if (IsReturnResult) {
                viewHolder.ll_point.setVisibility(View.GONE);
            } else if (model.code.equals("Mobile.Workflow")) {
                if (workflowTipsNum == 0) {
                    viewHolder.ll_point.setVisibility(View.GONE);
                } else {
                    viewHolder.ll_point.setVisibility(View.VISIBLE);
                    viewHolder.tv_point_num.setText("" + workflowTipsNum);
                }
            } else {
                if (tipNumList.containsKey(model.code) && !tipNumList.get(model.code).getAppCode().equals("0")) {
                    viewHolder.ll_point.setVisibility(View.VISIBLE);
                    viewHolder.tv_point_num.setText(tipNumList.get(model.code).getAppCode());
                } else {
                    viewHolder.ll_point.setVisibility(View.GONE);
                }
            }
            holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i(TAG, model.toString());
                    if (model != null) {
                        if (IsReturnResult) {
                            Intent it = new Intent();
                            it.putExtra("Data", model);
                            getAppActivity().setResult(Activity.RESULT_OK, it);
                            getAppActivity().onBackPressed();
                        } else {
                            if (model.code.equals("Mobile.Workflow")) {
                                Intent it = new Intent();
                                if (isShowDep && canOfficeClick) {
                                    it.setClassName(getActivity(), "com.i8office.android.zhihuixinwu.ui.dep.OfficeNewActivity");
                                } else {
                                    it.setClassName(getActivity(), "com.i8office.android.zhihuixinwu.ui.OfficeActivity");
                                }
                                startActivity(it);
                            }
                            else if (model.code.equals("Mobile.Calendar")) {
                                Intent it = new Intent();
                                it.setClassName(getActivity(), "com.i8office.android.zhihuixinwu.ui.schedule.ScheduleActivity");
                                startActivity(it);
                            }
                            else {
                                Intent it = new Intent(getActivity(), AutoFragment.class);
                                it.putExtra("Model", model);
                                startActivity(it);
                            }
                        }

                    }
                }
            });

        }
    }

    class ViewHolder {
        TextView text;
        ImageView img;
        FrameLayout ll_container;
        RelativeLayout ll_point;
        TextView tv_point_num;

    }


}
